<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="650px" @confirm="handleSubmit" @close="handleClose">
			<el-form ref="formRef" :model="formData" label-width="150px" :rules="formRules">
				<el-form-item label="最早可预定时间" prop="in_day">
					<el-select class="w-[280px]" v-model="formData.in_day">
						<el-option label="1天内" :value="1" />
						<el-option label="3天内" :value="3" />
						<el-option label="1周内" :value="7" />
						<el-option label="1月内" :value="30" />
					</el-select>
				</el-form-item>
				<el-form-item label="单次可预定最小时段" prop="min_minutes_per">
					<el-select class="w-[280px]" v-model="formData.min_minutes_per">
						<el-option label="30分钟" :value="30" />
					</el-select>
				</el-form-item>
				<el-form-item label="单次可预定最长时段" prop="max_minutes_per">
					<el-select class="w-[280px]" v-model="formData.max_minutes_per">
						<el-option label="无限制" :value="0" />
						<el-option label="30分钟" :value="30" />
						<el-option label="1小时" :value="60" />
						<el-option label="2小时" :value="120" />
						<el-option label="3小时" :value="180" />
					</el-select>
				</el-form-item>
			</el-form>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'
	import { officeConfigDetail, officeConfig } from '@/api/sharedoffice/sharedoffice';
	import Popup from '@/components/popup/index.vue';

	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()

	const popupTitle = computed(() => {
		return '会议室预定规则'
	})

	const formData = reactive({
		//最早可预订时间
		in_day: null,
		//单次可预定最小时段
		min_minutes_per: null,
		//单次可预定最长时段
		max_minutes_per: null
	})

	const formRules = {
		in_day: [
			{
				required: true,
				message: '请选择最早可预订时间',
				trigger: 'blur'
			}
		],
		min_minutes_per: [
			{
				required: true,
				message: '请选择单次可预定最小时段',
				trigger: 'blur'
			}
		],
		max_minutes_per: [
			{
				required: true,
				message: '请选择单次可预定最长时段',
				trigger: 'blur'
			}
		]
	}

	const handleSubmit = async () => {
		await formRef.value?.validate()
		let newFormData = JSON.parse(JSON.stringify(formData));
		await officeConfig(newFormData)
		popupRef.value?.close()
		emit('success')
	}

	const open = () => {
		popupRef.value?.open()
	}

	const getDetail = async () => {
		const data = await officeConfigDetail({});
		console.log(data);
		setFormData({in_day:data.in_day,min_minutes_per:data.min_minutes_per,max_minutes_per:data.max_minutes_per})
	}

	const setFormData = (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}
	}

	const handleClose = () => {
		emit('close')
	}

	defineExpose({ open, setFormData, getDetail })
</script>

<style scoped lang="scss"></style>